package com.mugui.spring.net.lock;

import com.mugui.spring.base.Filter;
import com.mugui.spring.base.Listener;
import com.mugui.spring.net.bean.Message;
import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.net.filter.FilterModel;
import com.mugui.spring.net.listener.ListenerModel;
import com.mugui.spring.net.session.SessionContext;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.http.HttpSession;

/**
 * 消息锁，重复消息直接屏蔽
 * 
 * @author Administrator
 *
 */
@Component
@Filter(value = { "*" }, weight = 99, type = Filter.POSITIVE)
@Listener(value = { "*" }, weight = 99, type = Filter.POSITIVE)
public class NetBagHandle implements FilterModel, ListenerModel {
	private static HashMap<String, byte[]> lock_map = new HashMap<>();

	@Override
	public NetBag filter(NetBag bag) {
		return lock(bag);

	}

	private NetBag lock(NetBag bag) {
		HttpSession session = SessionContext.getSession(bag.getSession());
		synchronized (lock_map) {
			if (lock_map.get(session.getId()) == null) {
				lock_map.put(session.getId(), new byte[0]);
			}
		}
		ReentrantLock key = null;
		synchronized (lock_map.get(session.getId())) {
			key = (ReentrantLock) session.getValue(bag.getFunc());
			if (key == null) {
				session.putValue(bag.getFunc(), key = new ReentrantLock());
			}
		}
		if (key.isLocked()) {
			return null;
		}
		key.lock();
		return bag;
	}

	@Override
	public void listener(Message message, NetBag bag) {
		HttpSession session = null;
		if (null == (session = SessionContext.getSession(bag.getSession()))) {
			return;
		}
		ReentrantLock key = (ReentrantLock) session.getValue(bag.getFunc());
		if (key != null) {
			if (key.isHeldByCurrentThread())
				key.unlock();
		}
	}


}
